package com.ld.service.impl;

import com.alibaba.fastjson.JSON;
import com.ld.service.RedisMqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisMqServiceImpl implements RedisMqService {

    private String key = "mq";
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public void receiveMessage() {
       new Thread(new ReceiveMessage()).start();
    }

    @Override
    public void sendMessage() {
        new Thread(new SendMessage()).start();
    }

    class ReceiveMessage implements Runnable {
        @Override
        public void run() {
            ListOperations<String,Object> listOperations = redisTemplate.opsForList();
            do{
                //设置为0 持续等待
                Object o = listOperations.rightPop(key,0, TimeUnit.SECONDS);
                System.out.println("接收的消息："+ JSON.toJSONString(o));
            }while (true);
        }
    }

    class SendMessage implements Runnable {

        @Override
        public void run() {
            for (int i=0;i<10;i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("发送消息：你好"+i);
                redisTemplate.opsForList().leftPush(key,"你好"+i);
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("发送消息：拜拜");
            redisTemplate.opsForList().leftPush(key,"拜拜");
        }
    }
}
